<?php

namespace common\models;

use yii\db\ActiveRecord;

class DateTimes extends ActiveRecord
{
    /**
     * 获取一年每周的开始日期和结束日期
     * @param $year
     * @return mixed
     */
    public static function get_week($year)
    {
        $year_start = $year . "-01-01";
        $year_end = $year . "-12-31";
        $startday = strtotime($year_start);
        if (intval(date('N', $startday)) != '1') {
            $startday = strtotime("next monday", strtotime($year_start)); //获取年第一周的日期
        }
        $year_mondy = date("Y-m-d", $startday); //获取年第一周的日期
        
        $endday = strtotime($year_end);
        if (intval(date('W', $endday)) == '7') {
            $endday = strtotime("last sunday", strtotime($year_end));
        }
        
        $num = 52;//一年约52周
        for ($i = 1; $i <= $num; $i++) {
            $j = $i - 1;
            $start_date = date("Y-m-d", strtotime("$year_mondy $j week "));
            
            $end_day = date("Y-m-d", strtotime("$start_date +6 day"));
            
            $week_array[$i] = [
                $start_date, $end_day];
        }
        return $week_array;
    }

    public static function getDays($start = '', $end = '') {
        if (empty($end)) {
            $end = date("Y-m-d");
        }

        if ($start > $end) {
            $tmp = $start;
            $start = $end;
            $end = $tmp;
        }

        $startUnix = strtotime($start);
        $endUnix = strtotime($end);

        $diff = ($endUnix - $startUnix) / 86400;

        return $diff + 1;
    }

    /**
     * 计算两个时间之间的差值，x天x时x分x秒
     * @param string $start
     * @param string $end
     * @return string
     */
    public static function getDiffTimes($start = '', $end = '') {
        $startUnix = strtotime($start);
        $endUnix = strtotime($end);

        $diff = $endUnix - $startUnix;

        $days = floor($diff / 86400);

        $hoursDiff = $diff - $days * 86400;
        $hours = floor($hoursDiff / 3600);

        $minutesDiff = $hoursDiff - $hours * 3600;
        $minutes = floor($minutesDiff / 60);

        $second = $minutesDiff - $minutes * 60;

        $res = '';
        if ($days > 0) {
            $res .= $days . "天";
        }

        if ($hours > 0) {
            $res .= $hours . "时";
        }

        if ($minutes > 0) {
            $res .= $minutes . "分";
        }

        if ($second > 0) {
            $res .= $second . "秒";
        }

        return $res;
    }
}
